package top.lightHearted.socket;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocketHandler class
 *
 * @author gpf
 * @date 2018/03/23
 */
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    static Map<String, WebSocketSession> USER_ID_TO_SESSION = new HashMap<>();

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        USER_ID_TO_SESSION.put(session.getId(), session);
        broadcastToTopic("WEBRTC", message.toString());
    }

    /**
     * 广播/订阅
     */
    public void broadcastToTopic(String topic, String message) {

        Topic destination = new ActiveMQTopic(topic);
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public javax.jms.Message createMessage(Session session) throws JMSException {
                javax.jms.TextMessage msg = session.createTextMessage(message);
                return msg;
            }
        });
    }

}
